﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Maticsoft.DBUtility;
using System.IO;
public partial class PersonCenter : System.Web.UI.Page
{
    PagedDataSource PDS = new PagedDataSource(); //PagedDataSource 实现分页  
    UserModel model;
    public string m_iID;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsLogin())
        {
            return;
        }
        if (!IsPostBack)
        {
            DataBinds();
        }
    }
    public void DataBinds()
    {
        int totalCount = 0;//总记录条数  
        int totalPage = 1;//总页数  
        string sql = "select * from TB_House where releasePerson="+model.Id;
        DataTable table = DbHelperOleDb.Fill(sql);
        totalCount = table.DefaultView.Count;
        PDS.DataSource = table.DefaultView; //设置pagedatasource 的属性        
        PDS.AllowPaging = true; //是否允许分页  
        PDS.PageSize = 10;//每页显示记录数量  
        int curPage;
        if (Request.QueryString["page"] != null)
            curPage = Convert.ToInt32(Request.QueryString["page"]);// 为四个链接准备  
        else
            curPage = 1;
        if (totalCount == 0)//如果没有记录，就一页  
            totalPage = 1;
        else
        {
            if (totalCount % PDS.PageSize == 0) //如果是整数页  
                totalPage = totalCount / PDS.PageSize;
            else
                totalPage = totalCount / PDS.PageSize + 1; //如果非整数页  
        }
        PDS.CurrentPageIndex = curPage - 1;
        lblCurrentPage.Text = "共" + totalCount.ToString() + "条记录，当前页" + curPage.ToString() + "/" + totalPage;
        lnkFrist.NavigateUrl = Request.CurrentExecutionFilePath + "?page=1";//获取当前请求的虚拟路径  
        if (!PDS.IsFirstPage) //如果不是第一页  
            lnkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + Convert.ToInt32(curPage - 1);
        if (!PDS.IsLastPage) //如果不是最后一页  
            lnkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + Convert.ToInt32(curPage + 1);
        lnkEnd.NavigateUrl = Request.CurrentExecutionFilePath + "?page=" + totalPage;
        rpCustomerInfo.DataSource = PDS;
        rpCustomerInfo.DataBind();
    }

    protected void btnNew_OnClick(object sender, EventArgs e)
    {
        ((Panel)rpCustomerInfo.Controls[0].FindControl("PlNew")).Visible = true;
    }

    private bool IsLogin()
    {
        if (Session["318User"] == null)
        {
            string js = "alert('请先登录!');window.location.href='../Login.aspx';";
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myjs", js, true);
            return false;
        }
        model = Session["318User"] as UserModel;
        return true;
    }
    protected void rpCustomerInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                DropDownList ddl2 = e.Item.FindControl("ddlAreaIDNew") as DropDownList;
                string strSQL2 = "select * from TB_Area";
                ddl2.DataSource = DbHelperOleDb.Fill(strSQL2);
                ddl2.DataTextField = "areaName";
                ddl2.DataValueField = "ID";
                ddl2.DataBind();
            }
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DropDownList ddl = e.Item.FindControl("ddlAreaIDEdit") as DropDownList;
                string strSQL = "select * from TB_Area";
                ddl.DataSource = DbHelperOleDb.Fill(strSQL);
                ddl.DataTextField = "areaName";
                ddl.DataValueField = "ID";
                ddl.DataBind();
                //设置选中值  
                DataRowView drv = (DataRowView)e.Item.DataItem;
                ddl.Items.FindByValue(drv["areaID"].ToString()).Selected = true;
                string userid = drv["ID"].ToString();
                if (userid != m_iID)
                {
                    ((Panel)e.Item.FindControl("plItem")).Visible = true;
                    ((Panel)e.Item.FindControl("plEdit")).Visible = false;
                }
                else
                {
                    ((Panel)e.Item.FindControl("plItem")).Visible = false;
                    ((Panel)e.Item.FindControl("plEdit")).Visible = true;
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            ((Panel)e.Item.FindControl("plEdit")).Visible = false;
        }
    }

    protected void rpCustomerInfo_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Save")
        {
            TextBox txtImage = e.Item.FindControl("saveImage") as TextBox;
            string image = txtImage.Text;
            if (string.IsNullOrEmpty(image))
            {
                image = "default.jpg";
            }
            int areaID = Convert.ToInt32((e.Item.FindControl("ddlAreaIDNew") as DropDownList).SelectedItem.Value);
            string address = (e.Item.FindControl("txtAddress") as TextBox).Text;
            string proportionSum = (e.Item.FindControl("txtProportionSum") as TextBox).Text;
            string rental = (e.Item.FindControl("txtRental") as TextBox).Text;
            string ownerPhone = (e.Item.FindControl("txtPhone") as TextBox).Text;
            string sql = "insert into TB_House (ID,areaID,address,proportionSum,rental,ownerPhone,releaseDate,saveImage,releasePerson) values (" + AddQuotes(GetGuid.Guid()) + ", " +
                "" + areaID + "," + AddQuotes(address) + "," + AddQuotes(proportionSum) + "," + AddQuotes(rental) + "," +
                AddQuotes(ownerPhone) + "," + AddQuotes(DateTime.Now.ToString()) + "," + AddQuotes(image) + ","+AddQuotes(model.Id)+")";
            DbHelperOleDb.ExecuteSql(sql);
        }
        else if (e.CommandName == "SaveCancel")
        {
            (e.Item.FindControl("PlNew") as Panel).Visible = false;
        }
        else if (e.CommandName == "Edit")
        {
            m_iID = e.CommandArgument.ToString();
        }
        else if (e.CommandName == "Cancel")
        {
            m_iID = null;
        }
        else if (e.CommandName == "Update")
        {
            string address = (e.Item.FindControl("txtAddressEdit") as TextBox).Text;
            int proportionSumEdit = Convert.ToInt32((e.Item.FindControl("proportionSumEdit") as TextBox).Text);
            string rentalEdit = (e.Item.FindControl("rentalEdit") as TextBox).Text;
            string ownerPhoneEdit = (e.Item.FindControl("ownerPhoneEdit") as TextBox).Text;
            int ddlAreaIDEdit = Convert.ToInt32((e.Item.FindControl("ddlAreaIDEdit") as DropDownList).SelectedItem.Value);
            string sql = "update TB_House set areaID=" + ddlAreaIDEdit + ",proportionSum=" + proportionSumEdit +
                ",rental=" + AddQuotes(rentalEdit) + ",ownerPhone=" + AddQuotes(ownerPhoneEdit)
                + ",address=" + AddQuotes(address) + " where ID=" + AddQuotes(e.CommandArgument.ToString()) + "";
            DbHelperOleDb.ExecuteSql(sql);
        }
        else if (e.CommandName == "Delete")
        {
            string sql = "delete from TB_House where ID=" + AddQuotes(e.CommandArgument.ToString()) + "";
            DbHelperOleDb.ExecuteSql(sql);
        }
        DataBinds();

    }
    private static bool IsAllowedExtension(FileUpload upfile)
    {
        FileStream fs = new FileStream(upfile.PostedFile.FileName, FileMode.Open, FileAccess.Read);
        BinaryReader r = new BinaryReader(fs);
        string fileclass = "";
        byte buffer;
        try
        {
            buffer = r.ReadByte();
            fileclass = buffer.ToString();
            buffer = r.ReadByte();
            fileclass += buffer.ToString();
        }
        catch
        {

        }
        r.Close();
        fs.Close();
        if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private string AddQuotes(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return "'0'";
        }
        return "'" + str + "'";
    }
}